<template>
  <div class="address-form-container">
    <div class="address-form">
      <h2>填写地址信息</h2>
      <form @submit.prevent="submitAddress">
        <div class="form-group">
          <label for="name">姓名：</label>
          <input type="text" id="name" v-model="address.addressLinkman" required />
        </div>

        <div class="form-group">
          <label for="phone">联系电话：</label>
          <input type="tel" id="phone" v-model="address.addressPhone" required />
        </div>

        <div class="form-group">
          <label for="district">区/县：</label>
          <select id="district" v-model="address.addressArea" required>
            <option value="" disabled selected>请选择区县</option>
            <option v-for="district in districts" :key="district" :value="district">
              {{ district }}
            </option>
          </select>
        </div>

        <div class="form-group">
          <label for="detail">详细地址：</label>
          <textarea id="detail" v-model="address.addressDetail" rows="3" required></textarea>
        </div>

        <button type="submit">提交地址</button>
      </form>
    </div>
  </div>
</template>

<style scoped>.address-form-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.address-form {
  background: #fff;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 500px;
}

.address-form h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.form-group {
  margin-bottom: 18px;
}

.form-group label {
  display: block;
  margin-bottom: 6px;
  font-weight: 500;
  color: #555;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ccc;
  border-radius: 6px;
  font-size: 14px;
  box-sizing: border-box;
}

.form-group select {
  appearance: none;
  background: url("data:image/svg+xml;charset=US-ASCII,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24'%3E%3Cpath fill='%23999' d='M7 10l5 5 5-5z'/%3E%3C/svg%3E") no-repeat right 10px center;
  background-size: 12px;
  padding-right: 30px;
}

.form-group textarea {
  resize: vertical;
  min-height: 60px;
}

button[type="submit"] {
  width: 100%;
  background-color: #1abc9c;
  color: white;
  border: none;
  padding: 12px;
  font-size: 16px;
  font-weight: bold;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

button[type="submit"]:hover {
  background-color: #16a085;
}
</style>

<script>
import {BASE_URL} from "@/util/Config.js";
import { useUserStore } from '@/stores/user';

export default {
  data() {
    return {
      address: {
        addressLinkman: '',
        addressPhone: '',
        addressDetail: '',
        addressArea: '',
      },
      districts: [],
      submittedAddress: null
    };
  },
  methods: {
    async fetchUserInfo() {
      const userStore = useUserStore();
      const userId = userStore.userInfo.userId;  // 假设你在 store 中保存的字段是 userId

      if (!userId) {
        alert('用户未登录或未获取到用户ID');
        return;
      }

      try {
        const response = await fetch(`${BASE_URL}/my/getInfo`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          credentials: 'include',
          body: JSON.stringify({
            userId: userId  // 发送用户 ID 到后端
          })
        });

        if (!response.ok) {
          throw new Error('获取用户信息失败');
        }

        const result = await response.json();

        if (result.code === 200 && result.data.length > 0) {
          const userInfo = result.data[0];
          this.address.addressLinkman = userInfo.userName || '';
          this.address.addressPhone = userInfo.userPhone || '';
        } else {
          throw new Error('接口返回数据异常');
        }
      } catch (error) {
        console.error('获取用户信息出错：', error);
        alert('无法获取用户信息');
      }
    },
    async submitAddress() {

      try {
        const response = await fetch(`${BASE_URL}/my/addAddresses`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          credentials: 'include',
          body: JSON.stringify(this.address)
        });

        if (!response.ok) {
          throw new Error('提交失败');
        }

        const result = await response.json();
        console.log('后端返回结果：', result);
        this.submittedAddress = { ...this.address };
        alert('地址提交成功！');
      } catch (error) {
        console.error('提交出错：', error);
        alert('提交失败，请检查网络或重试');
      }
      this.$router.push('/address')
    }
  },
  mounted() {
    this.districts = ['历下区', '市中区', '槐荫区', '天桥区', '历城区', '长清区','章丘区','济阳区','莱芜区','钢城区'];
    this.fetchUserInfo();
  }
};
</script>
